--[[
-- @Author: 671643387@qq.com
-- @Date: 2025-04-26 17:04
-- @Description: 开放式电脑工具箱
--]]

local component = require("component")
local text = require("text")
local sides = require("sides")

return {
    -- 休眠
    sleep = function (seconds)
        os.execute("sleep " .. seconds)
    end,

    -- 从控制台读取一个整数
    read_int = function ()
        return tonumber(string.format("%d", tonumber(io.read("*n"))))
    end,

    -- 从控制台读取一个字符串
    read_str = function ()
        repeat
            local input = io.read("*l")
            if #input > 0 then
                return input
            end
        until false
    end,

    -- 读取文件
    read_file = function (filename)
        local file = io.open(filename, "r")
        if file ~= nil then
            local content = file:read("*a")
            file:close()
            return content
        end
        return nil
    end,

    -- 保存文件
    save_file = function (filename, content)
        local file = io.open(filename, "w")
            if file ~= nil then
            file:write(content)
            file:flush()
            file:close()
            return true
        end
        return false
    end,

    -- 获取组件
    get_components = function (filter)
        local components = {}
        for address, name in component.list(filter) do
            components[address] = name
        end
        return components
    end,

    -- 清空红石信号
    clear_redstone = function (proxy)
        proxy.setOutput(sides.front, 0)
        proxy.setOutput(sides.back, 0)
        proxy.setOutput(sides.left, 0)
        proxy.setOutput(sides.right, 0)
        proxy.setOutput(sides.up, 0)
        proxy.setOutput(sides.down, 0)
    end,

    -- 将表内容带序号打印到控制台
    print_itable = function (table, prefix, key_padding)
        prefix = prefix or ""
        key_padding = key_padding or 0
        local index = 1
        for k, v in pairs(table) do
            print(string.format("%s%s %s %s",
                prefix, text.padRight(tostring(index), 2),
                text.padRight(tostring(k), math.max(key_padding, #tostring(k))), v))
            index = index + 1
        end
    end,

    -- 获取表数据数量
    get_table_size = function (table)
        local size = 0
        for _, _ in pairs(table) do
            size = size + 1
        end
        return size
    end,

    -- 获取表中指定位置的数据
    get_itable = function (table, index)
        for k, v in pairs(table) do
            index = index - 1
            if index == 0 then
                return k, v
            end
        end
        return nil, nil
    end,

    -- 获取当前毫秒
    get_tick = function ()
        return os.clock() * 1000
    end,

    -- 格式化数字字符串
    formatNumberWithCommas = function (num)
        local formatted = tostring(num):reverse():gsub("(%d%d%d)", "%1,")
        return formatted:reverse():gsub("^,", "")
    end
}
